#include <iostream>
#include <vector>
#include <stack>

using namespace std;
/**
 * Definition for a binary tree node.
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        postorderTv(root);
        return res;
    }
private:
    void postorderTv(TreeNode *root);
    vector<int> res;
    stack<TreeNode*> stk;
};

void Solution::postorderTv(TreeNode *root)
{
    TreeNode* prev = nullptr;
    while (root != nullptr || !stk.empty()) {
        while (root != nullptr) {
            stk.push(root);
            root = root->left;
        }
        root = stk.top();
        if (root->right == nullptr || root->right == prev) { //可以弹出
            res.push_back(root->val);
            stk.pop();
            prev = root;
            root = nullptr;
        } else { // 继续访问其right
            root = root->right;
        }
    }
}